package com.example.hospitalsystem.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hospitalsystem.exception.HospitalSystemServiceException;
import com.example.hospitalsystem.mapper.*;
import com.example.hospitalsystem.pojo.dto.registration.AddRegistionDto;
import com.example.hospitalsystem.pojo.dto.registration.RegistrationpageQueryDto;
import com.example.hospitalsystem.pojo.dto.registration.UpdateBalanceDTO;
import com.example.hospitalsystem.pojo.entity.*;
import com.example.hospitalsystem.pojo.vo.RegistrationInfoVO;
import com.example.hospitalsystem.result.Result;
import com.example.hospitalsystem.result.ResultCodeEnum;
import com.example.hospitalsystem.service.RegistrationService;
import com.example.hospitalsystem.utils.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class RegistrationServiceImpl extends ServiceImpl<RegistrationMapper, Registration> implements RegistrationService {

    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private RegistrationMapper registrationMapper;


    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<Object> getRegistrationPage(RegistrationpageQueryDto registrationpageQueryDto) {

        /**
         * 分页获取全部挂号信息
         */
        String token = request.getHeader("Authorization");
        Integer userId = jwtHelper.getUserId(token);
        Integer role = jwtHelper.getRole(token);
        if (!Integer.valueOf(3).equals(role)) {
            throw new HospitalSystemServiceException(ResultCodeEnum.ILLEGAL_OPERATION, "您不是门诊医生，无权查看该信息");
        }
        Page<Registration> registrationPage=new Page<>(
                registrationpageQueryDto.getPageNum(),registrationpageQueryDto.getPageSize());

        IPage<Registration> registrationPageIPage=baseMapper.selectPage(registrationPage,null);

        List<Registration> registrationList = registrationPageIPage.getRecords();

        if (registrationList.isEmpty() || registrationList.size() == 0) {
            throw new HospitalSystemServiceException(ResultCodeEnum.DATABASE_ERROR, "暂时没有人预约挂号");
        }

        List<RegistrationInfoVO> registrationInfoVOS = new ArrayList<>();
        for (Registration registration : registrationList) {
            RegistrationInfoVO registrationInfoVO = convertToRegistrationInfoVO(registration);
            registrationInfoVOS.add(registrationInfoVO);
        }

        return Result.ok(registrationInfoVOS);
    }

    /**
     * 将Registration对象转换为RegistrationInfoVO对象
     * @param registration
     * @return
     */
    private RegistrationInfoVO convertToRegistrationInfoVO(Registration registration) {
        RegistrationInfoVO registrationInfoVO = new RegistrationInfoVO();
        registrationInfoVO.setRegistrationId(registration.getRegistrationId());
        registrationInfoVO.setRegistrationTime(registration.getRegistrationTime());
        registrationInfoVO.setPatientName(registration.getPatientName());
        registrationInfoVO.setGender(registration.getGender());
        registrationInfoVO.setAge(registration.getAge());
        registrationInfoVO.setIdentity(registration.getIdentity());
        registrationInfoVO.setDepartmentName(registration.getDepartmentName());
        LambdaQueryWrapper<Doctor> doctorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        doctorLambdaQueryWrapper.eq(Doctor::getDoctorName, registration.getDoctorName());
        Doctor doctor = doctorMapper.selectOne(doctorLambdaQueryWrapper);
        registrationInfoVO.setDoctorName(doctor.getDoctorName());
        registrationInfoVO.setDiseaseDescription(registration.getDiseaseDescription());

        return  registrationInfoVO;
    }

    /**
     * 预约挂号
     * @param addRegistionDto
     * @return
     */
    @Override
    @Transactional
    public Result<Object> addRegistrationInfo(AddRegistionDto addRegistionDto) {
        String token = request.getHeader("Authorization");
        Integer userId = jwtHelper.getUserId(token);
        Integer role = jwtHelper.getRole(token);
        //用户是否为患者
        if (!Integer.valueOf(4).equals(role)) {
            throw new HospitalSystemServiceException(ResultCodeEnum.ILLEGAL_OPERATION, "该用户与角色不匹配");
        }
        Registration registration = new Registration();
        BeanUtils.copyProperties(addRegistionDto, registration);
        LambdaQueryWrapper<Patient> patientLambdaQueryWrapper = new LambdaQueryWrapper<>();
        patientLambdaQueryWrapper.eq(Patient::getUserId, userId);
        Patient patient = patientMapper.selectOne(patientLambdaQueryWrapper);

        LambdaQueryWrapper<Doctor> doctorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        doctorLambdaQueryWrapper.eq(Doctor::getDoctorName, addRegistionDto.getDoctorName());
        Doctor doctor = doctorMapper.selectOne(doctorLambdaQueryWrapper);

        LambdaQueryWrapper<Registration> registrationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        registrationLambdaQueryWrapper.eq(Registration::getPatientName, patient.getPatientName());
        if (registrationMapper.selectOne(registrationLambdaQueryWrapper) != null) {
            throw new HospitalSystemServiceException(ResultCodeEnum.ILLEGAL_OPERATION, "您已挂号，请勿重复此操作");
        }
        //封装挂号信息
        registration.setRegistrationId(new Random().nextInt(900000)+100000);
        registration.setPatientId(patient.getPatientId());
        registration.setPatientName(patient.getPatientName());
        registration.setGender(patient.getGender());
        registration.setBornDate(patient.getBornDate());
        registration.setAge(patient.getAge());
        registration.setContact(patient.getContact());
        registration.setAddress(patient.getAddress());
        registration.setIdentity(patient.getIdentity());
        registration.setDepartmentName(doctor.getDepartmentName());
        registration.setDepartmentKind(doctor.getDepartmentKind());
        registration.setDoctorName(doctor.getDoctorName());
        registration.setRegistrationFee(addRegistionDto.getRegistrationFee());
        registration.setDiseaseDescription(addRegistionDto.getDiseaseDescription());
        registration.setRegistrationTime(LocalDate.now());
        registrationMapper.insert(registration);

        //患者扣除挂号费用
        UpdateBalanceDTO updateBalanceDTO = new UpdateBalanceDTO();
        updateBalanceDTO.setPatientId(patient.getPatientId());
        updateBalanceDTO.setRegistrationFee(registration.getRegistrationFee());
        int row = patientMapper.updateBalanceForRegistrationFee(updateBalanceDTO);
        if(row != 1) {
            throw new HospitalSystemServiceException(ResultCodeEnum.ILLEGAL_OPERATION, "该用户余额不足，请先充值");
        }
        return Result.ok(ResultCodeEnum.SUCCESS, "患者挂号成功");
    }



    /**
     * 批量删除挂号信息
     * @param ids
     */
    @Override
    public void deleteBatchRegistration(List<Integer> ids) {

        registrationMapper.deleteBatchIds(ids);
    }

    /**
     * 返回挂号列表
     * @return
     */
    @Override
    public List<Registration> getRegistrationList() {
//        String token = request.getHeader("Authorization");
//        Integer role = jwtHelper.getRole(token);
//        if (!role.equals(3)) {
//            throw new HospitalSystemServiceException(ResultCodeEnum.ILLEGAL_OPERATION,"非医务工作人员，请勿点击");
//        }
        LambdaQueryWrapper<Registration> queryWrapper = new LambdaQueryWrapper<>();
        List<Registration> list = registrationMapper.selectList(queryWrapper);
        return list;
    }


}
